package com.example;


/**
 * @Author loubobooo
 * @Description #234. 回文链表
 * @Date 2022/2/21
 */
public class PalindromeLinkedList {

    /**
     * 方法描述:给你一个单链表的头节点 head ，请你判断该链表是否为回文链表。如果是，返回 true ；否则，返回 false 。
     * 示例 1：
     * 输入：head = [1,2,2,1]
     * 输出：true
     *
     * @param: [head]
     * @return: boolean
     * @author: loubobooo
     * @date: 2022/2/25
     */
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode secondHalf = slow.next;
        // 解决奇数和偶数不同链表
        if (fast.next != null) {
            secondHalf = slow.next.next;
        }
        // 断开slow后续的节点
        slow.next = null;
        return equals(secondHalf, reverseList(head));
    }

    private boolean equals(ListNode l1, ListNode l2) {
        while (l1 != null && l2 != null) {
            if (l1.val != l2.val) {
                return false;
            }
            l1 = l1.next;
            l2 = l2.next;
        }
        return l1 == null && l2 == null;
    }

    private ListNode reverseList(ListNode listNode) {
        if (listNode == null) {
            return listNode;
        }
        ListNode prev = null;
        ListNode cur = listNode;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(-1);
        ListNode cur = listNode;
        for (int i = 1; i <= 3; i++) {
            cur.next = new ListNode(i);
            cur = cur.next;
        }
        for (int i = 2; i >=1; i--) {
            cur.next = new ListNode(i);
            cur = cur.next;
        }

        PalindromeLinkedList p = new PalindromeLinkedList();
        p.reorderList(listNode.next);
    }

    public void reorderList(ListNode head){
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode fast = dummy;
        ListNode slow = dummy;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next;
            if(fast.next != null){
                fast = fast.next;
            }
        }
        ListNode temp = slow.next;
    }
}
